package com.mobi.Survey.lib.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;

import com.mobi.Survey.lib.activities.AlarmReciver;
import com.mobi.Survey.lib.model.AlarmPojo;

/**
 * 
 * <p>
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * Helper.java Provides different sort of helper utility
 * 
 * 
 */
public class Helper {

	public static final String APP_FOLDER = "survey";

	public static final int toInt(String numString) {

		try {
			return Integer.parseInt(numString.trim());
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static final byte toByte(String numString) {

		try {
			return Byte.parseByte(numString.trim());
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static final boolean toBoolean(String boolStr) {

		try {
			return "true".equalsIgnoreCase(boolStr) || "1".equals(boolStr);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static final long toLong(String numString) {

		try {
			return Long.parseLong(numString.trim());
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static final Double toDouble(String numString) {

		try {
			return Double.parseDouble(numString.trim());
		} catch (Exception e) {
			e.printStackTrace();
			return 0.0;
		}
	}

	private static final int CONNECTION_TIME_OUT = 12000;// ms
	private static final int SO_TIME_OUT = 12000; // ms

	/**
	 * Download file from internet of given url
	 * 
	 * @param fromUrl
	 * @param toPath
	 *            destination path i.e /sdcard/survey/your file
	 * @throws IOException
	 */
	public static void downloadFile(String fromUrl, String toPath) throws IOException {
		Log.i(Helper.class.getSimpleName(), "Downloading: " + fromUrl);
		InputStream input = null;
		OutputStream output = null;
		try {
			URL url1 = new URL(fromUrl);
			URLConnection conexion = url1.openConnection();
			conexion.setConnectTimeout(CONNECTION_TIME_OUT);
			conexion.connect();

			input = new BufferedInputStream(url1.openStream());

			output = new FileOutputStream(toPath);

			byte data[] = new byte[512];
			int count = 0;
			while ((count = input.read(data)) != -1) {

				output.write(data, 0, count);
			}
		} finally {
			if (output != null) {
				output.flush();
				output.close();
			}
			if (input != null)
				input.close();
		}

	}

	public static final float toFloat(String numString) {

		try {
			return Float.parseFloat(numString.trim());
		} catch (Exception e) {

			return 0;
		}
	}

	/**
	 * Path to application specific folder with name {@value #APP_FOLDER}
	 * 
	 * @return
	 */
	public static final String getPathToAppFolder() {
		return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + APP_FOLDER + File.separator;
	}

	/**
	 * 
	 * @param path
	 * @return
	 */
	public static boolean createDirIfNotExists(String path) {
		boolean ret = true;

		File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), path);

		try {
			if (!file.exists()) {
				if (!file.mkdirs()) {

					ret = false;
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (Exception e) {

			e.printStackTrace();
		}

		return ret;
	}

	/**
	 * For optimization we reduce image quality to not to run Out Of Memory
	 * 
	 * @param file
	 * @param quality
	 *            1 ......n, 1 means maximum quality
	 * @return
	 */
	public static Bitmap decode70x70(String file, int quality) {
		BitmapFactory.Options o2 = null;
		try {

			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(file, o);

			final int REQUIRED_WIDTH = 70;
			final int REQUIRED_HEIGHT = 70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;

			int scale = quality;

			scale = quality;
			while (true) {
				if (width_tmp / 2 < REQUIRED_WIDTH || height_tmp / 2 < REQUIRED_HEIGHT)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}
			o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
		} catch (Exception e) {

		}
		try {
			return BitmapFactory.decodeFile(file, o2);
		} catch (Exception e) {

			return null;
		}

	}

	/**
	 * For optimization we reduce image quality to not to run Out Of Memory
	 * 
	 * @param file
	 * @param quality
	 *            1 ......n, 1 means maximum quality
	 * @return
	 */
	public static Bitmap decode150x150(String file, int quality) {
		BitmapFactory.Options o2 = null;
		try {

			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(file, o);

			final int REQUIRED_WIDTH = 150;
			final int REQUIRED_HEIGHT = 150;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;

			int scale = quality;

			scale = quality;
			while (true) {
				if (width_tmp / 2 < REQUIRED_WIDTH || height_tmp / 2 < REQUIRED_HEIGHT)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}
			o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
		} catch (Exception e) {

		}
		try {
			return BitmapFactory.decodeFile(file, o2);
		} catch (Exception e) {

			return null;
		}

	}
	
	

	/**
	 * For optimization we reduce image quality to not to run Out Of Memory
	 * 
	 * @param file
	 * @param quality
	 *            1 ......n, 1 means maximum quality
	 * @return
	 */
	public static Bitmap decode(String file, int quality) {
		BitmapFactory.Options o2 = null;
		try {

			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(file, o);

			final int REQUIRED_WIDTH = 320;
			final int REQUIRED_HEIGHT = 480;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;

			int scale = quality;

			scale = quality;
			while (true) {
				if (width_tmp / 2 < REQUIRED_WIDTH || height_tmp / 2 < REQUIRED_HEIGHT)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}
			o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
		} catch (Exception e) {

		}
		try {
			return BitmapFactory.decodeFile(file, o2);
		} catch (Exception e) {

			return null;
		}

	}

	/**
	 * 
	 * @param file
	 * @return
	 */
	public static final boolean isFileExist(String file) {
		File f = new File(file);
		return f.exists();

	}

	public static final String getTempFileFromUrl(String url) {

		return getTempFile(getHashNameFromUrl(url) + "");
	}

	/**
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getTempFile(String fileName) {
		String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + APP_FOLDER;

		return filepath + File.separator + fileName;
	}

	public static final int getHashNameFromUrl(String url) {
		if (url == null)
			url = "";
		if (url.length() == 0) {

			return 0;
		}
		return url.hashCode();

	}

	/**
	 * Send get request to download data from server
	 * 
	 * @param url
	 * @param xml
	 * @return
	 * @throws IOException
	 * @throws
	 */
	public static String performGetOperation(String url) throws IOException {
		StringBuilder builder = new StringBuilder();
		HttpGet httpGet = new HttpGet(url);
		HttpParams httpParameters = new BasicHttpParams();

		HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIME_OUT);

		HttpConnectionParams.setSoTimeout(httpParameters, SO_TIME_OUT);

		DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
		HttpResponse response = httpClient.execute(httpGet);

		StatusLine statusLine = response.getStatusLine();

		int statusCode = statusLine.getStatusCode();
		if (statusCode == 200) {
			HttpEntity entity = response.getEntity();
			InputStream content = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(content), 1024);
			String line;
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
		} else {
			return null;
		}
		return builder.toString();
	}

	public static InputStream performGetOperationI(String url) throws IOException {

		HttpGet httpGet = new HttpGet(url);
		HttpParams httpParameters = new BasicHttpParams();

		HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIME_OUT);

		HttpConnectionParams.setSoTimeout(httpParameters, SO_TIME_OUT);

		DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
		HttpResponse response = httpClient.execute(httpGet);

		StatusLine statusLine = response.getStatusLine();

		int statusCode = statusLine.getStatusCode();

		if (statusCode == 200) {

			return response.getEntity().getContent();
		}

		return null;
	}

	/**
	 * 
	 * @param ctx
	 * @return
	 */
	public static boolean isNetworkAvailable(Context ctx) {
		NetworkInfo activeNetworkInfo = null;
		try {
			ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
			activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

			if (activeNetworkInfo == null) {
				return false;
			} else if (activeNetworkInfo.isConnected() && activeNetworkInfo.isAvailable()) {
				return true;
			} else {
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return true;
	}

	public static final void delete(File f) {
		try {
			if (f.isDirectory()) {
				for (File c : f.listFiles())
					delete(c);
			}
			if (!f.getName().equals(Helper.APP_FOLDER))
				f.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	

	public static final long stringTimeToMillis(String hourMinuteSecString) {

		long limit = 0;
		if ( hourMinuteSecString.length() == 8) {

			String[] limits = hourMinuteSecString.split(":");
			try {
				int hour = Integer.parseInt(limits[0]);
				int minute = Integer.parseInt(limits[1]);
				int sec = Integer.parseInt(limits[2]);

				hour *= 60 * 60 * 1000;
				minute *= 60 * 1000;
				sec *= 1000;
				limit = hour + minute + sec;
			} catch (NumberFormatException e) {
				Log.e("AlarmScreen", "Invalid Limit: " + hourMinuteSecString);
			}

		}

		return limit;

	}

	public static void setAlarm(Context ctx, AlarmPojo attr) {
		Intent myIntent = new Intent(ctx, AlarmReciver.class);

		myIntent.putExtra("attributes", attr);

		PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, attr.getPendingIntentId(), myIntent, PendingIntent.FLAG_CANCEL_CURRENT);

		AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
 
	 
		alarmManager.set(AlarmManager.RTC_WAKEUP, attr.getTriggerTime(), pendingIntent);
	}
}
